for_each (terraform)
リソースやモジュールを複数作成するときに使う
繰り返しをリストやマップで指定して、要素ごとにリソースを展開する
例
code:hcl(rb)
variable "instances" {
default = {
web = {
ami = "ami-123456"
type = "t2.micro"
}
db = {
ami = "ami-654321"
type = "t2.small"
}
}
}
resource "aws_instance" "example" {
for_each = var.instances # 使用
ami = each.value.ami
instance_type = each.value.type
}
output "instance_ids" {
value = {for k, inst in aws_instance.example : k => inst.id}
}
結果として下記2つが作成される
aws_instance.example["web"]
aws_instance.example["db"]
collectionに対してループして、each.keyとeach.valueでアクセスできる
each.key → マップのキー("web" や "db")
each.value → マップの値({ ami = "...", type = "..." })